import third from '/shop/api/third';
import $wxsdk from '/shop/libs/sdk-h5-weixin';

import $platform from '/shop/platform';
import { getRootUrl } from '/shop/helper';
import $userStore from '/shop/store/user.js'
import $app from '/shop/store/app.js'
// 加载微信公众号JSSDK
async function load() {
	if (
		$app().platform.auto_login &&
		!$userStore().isLogin &&
		location.href.search('pages/index/login') === -1
	) {
		// 发起自动登陆
		login();
	}
	$wxsdk.init();
}

// 微信公众号登陆
async function login(code = '') {
	// 获取登陆地址
	if (!code) {
		const loginResult = await getLoginUrl();
		if (loginResult.code === '0' && loginResult.data.oauthUrl) {
			uni.setStorageSync('returnUrl', location.href);
			window.location = loginResult.data.oauthUrl;
		}
	} else {
		// 解密code发起登陆
		const loginResult = await loginByCode(code);
		if (loginResult.code === '0') {
			$userStore().setToken(loginResult.data.token);
			return loginResult;
		}
	}
	return false;
}

// 微信公众号绑定
async function bind(code = '') {
	// 获取绑定地址
	if (code === '') {
		const loginResult = await getLoginUrl('bind');
		if (loginResult.error === 0 && loginResult.data.login_url) {
			uni.setStorageSync('returnUrl', location.href);
			window.location = loginResult.data.login_url;
		}
	} else {
		// 解密code发起登陆
		const loginResult = await bindByCode(code);
		if (loginResult.error === 0) {
			return loginResult;
		}
	}
	return false;
}

// 微信公众号解除绑定
async function unbind() {
	const { error } = await third.wechat.unbind({
		platform: 'officialAccount',
	});
	return Promise.resolve(!error);
}

// 获取公众号登陆地址
function getLoginUrl(event = 'login') {
	let page = getRootUrl() + 'pages/index/login';
	return third.wechat.oauthLogin({
		platform: 'officialAccount',
		page: page,
		execution: event,
	});
}

// 此处使用前端发送code在后端解密，防止用户在后端过长时间停留
function loginByCode(code) {
	return third.wechat.login({
		platform: 'officialAccount',
		code: code,
	});
}

// 此处使用前端发送code在后端解密，防止用户在后端过长时间停留
function bindByCode(code) {
	return third.wechat.bind({
		platform: 'officialAccount',
		payload: encodeURIComponent(
			JSON.stringify({
				code,
			}),
		),
	});
}

export default {
	load,
	login,
	bind,
	unbind,
	jssdk: $wxsdk,
};
